package logger

import (
	"DCOS-API/config"
	"fmt"
	"github.com/lestrrat-go/file-rotatelogs"
	"github.com/rifflock/lfshook"
	log "github.com/sirupsen/logrus"
	"runtime"
	"time"
)

func newLfsHook(level log.Level, maxRemainCnt uint) log.Hook {
	logPath := config.GetConfig().BaseConfig.LogPath
	sysType := runtime.GOOS
	if logPath == "" {
		if sysType == "windows" {
			logPath = ".\\logfiles"
		} else {
			logPath = "./logfiles"
		}
	}
	var logName string
	if sysType == "windows" {
		logName = fmt.Sprintf("%s\\dcos-api",logPath)
	} else {
		logName = fmt.Sprintf("%s/dcos-api",logPath)
	}

	writer, err := rotatelogs.New(
		logName+".%Y%m%d%H",
		// WithLinkName为最新的日志建立软连接，以方便随着找到当前日志文件
		rotatelogs.WithLinkName(logName),
		// WithRotationTime设置日志分割的时间，这里设置为一小时分割一次
		rotatelogs.WithRotationTime(time.Hour),
		// WithMaxAge和WithRotationCount二者只能设置一个，
		// WithMaxAge设置文件清理前的最长保存时间，
		// WithRotationCount设置文件清理前最多保存的个数。
		//rotatelogs.WithMaxAge(time.Hour*24),
		rotatelogs.WithRotationCount(maxRemainCnt),
	)

	if err != nil {
		log.Errorf("config local file system for logger error: %v", err)
	}

	lfsHook := lfshook.NewHook(lfshook.WriterMap{
		level: writer,
	}, &log.JSONFormatter{
		TimestampFormat:   "2006-01-02 15:04:05",
	})

	return lfsHook
}
